package com.bp.hearthealth.pulse.lnapps.bp_network

import androidx.lifecycle.Observer
import com.bp.hearthealth.pulse.lnapps.bp_extension.showToast

abstract class BpIStateObserver<T> : Observer<BaseResp<T>> {
    override fun onChanged(t: BaseResp<T>) {
        when (t.dataState) {
            DataState.STATE_SUCCESS -> {
                if (t.isSuccess) {
                    onDataChange(t.data)
                } else {
                    onFaild(t)
                }
            }

            DataState.STATE_EMPTY -> {
                onDataEmpty(t)
            }

            DataState.STATE_FAILED -> {
                onFaild(t)
            }

            DataState.STATE_ERROR -> {
                t.error?.let {
                    if (t.msg != null) {
                        t.msg?.showToast()
                    }
                    onError(it)
                }
            }

            else -> {
            }
        }
    }

    //请求数据且数据不为空
    open fun onDataChange(data: T?) {}

    //请求成功，但数据为空
    open fun onDataEmpty(t: BaseResp<T>) {}

    //请求成功，但code不为0
    open fun onFaild(t: BaseResp<T>) {}

    //请求错误
    open fun onError(e: Throwable?) {}

    //弹Toast
    private fun showToast(msg: String) {
        msg.showToast()
    }
}